package com.corpgovernment.organization.mq;

import com.corpgovernment.common.mq.consumer.AbstractMultiTenantRocketMQConsumer;
import com.corpgovernment.common.mq.enums.MessageBizTypeEnum;
import com.corpgovernment.organization.entity.SyncEmployeeRequestEntity;
import com.corpgovernment.organization.service.ISyncEmployeeService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class MultiTenantSyncEmployeeConsumer extends AbstractMultiTenantRocketMQConsumer {

    @Autowired
    private ISyncEmployeeService syncEmployeeService;

    /**
     * 消费消息
     *
     * @param messageExt
     * @param context
     * @throws Exception
     */
    @Override
    protected void consume(MessageExt messageExt, ConsumeConcurrentlyContext context) {
        if (messageExt == null || !MessageBizTypeEnum.SYNC_EMPLOYEE_NEW.getTopic().equals(messageExt.getTopic())) {
            log.error("[SyncEmployeeMsgConsumer]收到了没有订阅的消息[{}]", messageExt);
            return;
        }

        try {
            // 获取消息内容
            String msg = new String(messageExt.getBody(), StandardCharsets.UTF_8);
            log.info("[MsgId[{}]，SyncEmployeeMsgConsumer]接受到的消息[{}]", messageExt.getMsgId(), msg);

            // 反序列化消息
            SyncEmployeeRequestEntity entity = JsonUtils.parse(msg, SyncEmployeeRequestEntity.class);
            if (entity == null || CollectionUtils.isEmpty(entity.getEmployeeInfoList())) {
                return;
            }
            // 消息Tag
            String tags = messageExt.getTags();
            syncEmployeeService.syncEmployeeInfo(entity);
        } catch (Exception ex) {
            log.error("SyncEmployeeMsgConsumer.consume", ex);
        }
    }

    @Override
    protected MessageBizTypeEnum getMessageBizType() {
        return MessageBizTypeEnum.SYNC_EMPLOYEE_NEW;
    }

}
